package spring.cloud.tasks.executor.executor.task.task_item_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import static spring.cloud.tasks.common.Threads.sleep;

@Slf4j
@Setter
@Getter
public class TaskItemExecuteTaskKill {
    /**
     * 延迟kill 尽可能让任务执行完毕
     */
    public static void kill(TaskItemExecuteTask taskItemFutureTask) {
        TaskItemExecute taskItemExecute = taskItemFutureTask.getTaskItemExecute();
        taskItemExecute.needStop = true;//告知程序终止当前的任务。
        //
        for (int i = 1; i <= 3; i++) {
            sleep();
        }
        Thread currentThread = taskItemExecute.getTaskItemExecuteTaskThread();
        if (currentThread == null) {
            log.warn("需要进行强杀的任务线程不存在");
            return;
        } else {
            currentThread.interrupt();//唤醒睡眠的任务线程,唤醒以后很快就被需要被告知程序终止当前的任务。
            //
            if (!taskItemExecute.isExecuted()) {
                for (int i = 1; i <= 60; i++) {
                    if (taskItemExecute.isExecuted()) {
                        return;
                    }
                    sleep();
                }
            }
            try {
                log.warn("强杀的任务线程仍然没有执行完,现在调用thread.stop()进行强杀");
                // stop thread
                currentThread.stop();
            } catch (Exception e) {
            }
            log.warn("强杀的任务线程流程执行在最后了");
            return;
        }
    }

}
